package com.zhidisoft.base.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.zhidisoft.common.ResultData;
import com.zhidisoft.system.entity.User;
import com.zhidisoft.system.service.IFunctionService;
import com.zhidisoft.system.service.IMenuService;
import com.zhidisoft.system.service.IRoleService;
import com.zhidisoft.system.service.IUserService;

@SuppressWarnings("all")
public abstract class BaseAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	/**
	 * 把所有的Service注入给BaseAction
	 */
	@Autowired
	protected IUserService userService;
	
	@Autowired
	protected IRoleService roleService;
	
	@Autowired
	protected IFunctionService funcService;
	
	@Autowired
	protected IMenuService menuService;
	
	/**
	 * 封装响应信息
	 */
	protected ResultData resultData;
	
	/**
	 * 用于接收分页页码
	 */
	protected Long page = 1L;
	
	/**
	 * 记录数
	 */
	protected Long rows = 20L;

	public ResultData getResultData() {
		return resultData;
	}

	public void setResultData(ResultData resultData) {
		this.resultData = resultData;
	}
	
	/**
	 * 获取到当前登录用户的信息
	 * @return
	 */
	protected User getCurrentUser(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		return (User)session.getAttribute("user");
	}
	
	
	public Long getPage() {
		return page;
	}

	public void setPage(Long page) {
		this.page = page;
	}

	public Long getRows() {
		return rows;
	}

	public void setRows(Long rows) {
		this.rows = rows;
	}

	/**
	 * 把对象转换为json格式并且输出至客户端
	 * @param obj
	 * @throws IOException
	 */
	protected void printJSONObject(Object obj) throws IOException{
		printJSONObject(obj, new String[]{});
	}
	
	/**
	 * 将对象转换为json格式并且输出至客户端
	 * @param obj
	 * @param excludeProperties -将会被配置属性
	 * @throws IOException
	 */
	protected void printJSONObject(Object obj, String... excludeProperties) throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		
		JsonConfig config = new JsonConfig();
		config.setExcludes(excludeProperties);
		
		JSONObject json = JSONObject.fromObject(obj, config);
		
		out.print(json.toString());
		out.flush();
	}
	
	
	

}
